<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item label="部门名称">
					<el-input v-model="filters.keyword" placeholder="部门名称"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-select v-model="formInline.region" placeholder="状态">
						<el-option label="开启" value="0"></el-option>
						<el-option label="禁用" value="-1"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="query">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>
		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" label="序号" align="center" width="100">
			</el-table-column>
			<el-table-column prop="sn" label="部门编号" align="center" width="170" >
			</el-table-column>
			<el-table-column prop="name" label="部门名称" align="center" width="170" >
			</el-table-column>
			<el-table-column prop="state" label="状态" align="center" width="170" >
				<template scope="scope">
					<span style="color: green"  v-if="scope.row.state==0" size="small">启动</span>
					<span style="color: red" v-else-if="scope.row.state==-1" size="small">禁用</span>
					<span style="color: orange" v-else size="small">未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="employee.username" label="部门领导" align="center" width="170" >
			</el-table-column>
			<el-table-column prop="department.name" label="上级部门" align="center" min-width="170" >
			</el-table-column>
			<el-table-column label="操作" align="center" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-divider><i class="el-icon-mobile-phone"></i></el-divider>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
						   @current-change="handleCurrentChange"
						   :current-page="currentPage"
						   :page-size="pageSize"
						   :total="total"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="editForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="0">开启</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<!--
				v-for  遍历
				:key="item.id"  唯一标识
				:label="item.label" 显示到页面的内容
				:value="item.value  传到后台的数据
				-->
				<el-form-item label="部门领导" prop="employee">
					<el-select v-model="editForm.employee" placeholder="请选择" value-key="id">
						<el-option
								v-for="item in employees"
								:key="item.id"
								:label="item.username"
								:value="item">
							<span style="float: left">{{ item.username }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<!--<el-input v-model="editForm.parent" auto-complete="off"></el-input>
				label: name: 页面展示数据
				value : 向后台传的数据
				-->
				<el-form-item label="上级部门" prop="department">
					<el-cascader v-model="editForm.department"
								 :options="options"
								 :props="{
									checkStrictly: true,
									value: 'id',
									label: 'name'
							 	}"
								 clearable>
					</el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
                    keyword: ''
				},
                formInline: {
                    user: '',
                    region: ''
                },
				departments: [],
				employees: [],
                options:[],
                currentPage: 1,
                pageSize:5,
                total: 0,
                title:'',
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
                    name: [
                        { required: true, message: '请输入部门名称', trigger: 'blur' }
                    ],
                    sn: [
                        { required: true, message: '请输入部门编号', trigger: 'blur' }
                    ]
				},
				//编辑界面数据
				editForm: {
					id: null,
					name: '',
                    sn: '',
                    state: 0,
                    employee:null,
                    department:null
				},
			}
		},
		methods: {
		    //点击查询
            query(){
              this.currentPage=1;//将每次点击查询后，当前页设置为第一页
              this.getDepartments();
            },
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepartments();
			},
			//获取上级部门
			getTree(){
			    //发送请求
				this.$http.get("/dept/tree")
					.then(res=>{
                        this.options=res.data;
					}).catch(res=>{

				})
			},
			//获取员工的方法
            getEmployees(){
			    //发送请求
                this.$http.get("/emp").then(res=>{
					this.employees=res.data;
				}).catch(res=>{

				})
			},
			//获取用户列表
			getDepartments() {
				let para = {
                    currentPage: this.currentPage,//当前页
                    pageSize:this.pageSize,//每页显示条数
                    keyword: this.filters.keyword,//根据条件查询
                    state: this.formInline.region//状态
				};
				this.listLoading = true;
				//发送请求
				this.$http.post("/dept",para).then(result=>{
				    this.departments=result.data.pageData;
				    this.total=result.data.totals;
                    this.listLoading = false;
				}).catch(result=>{
				    alert("系统异常...");
				})
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					//let para = { id: row.id };//获取每条id
					//发送请求
					this.$http.delete("/dept/"+row.id).then(res=>{//删除成功
                        this.listLoading = false;//关闭加载圈圈
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        //删除成功后调用方法，刷新列表
                        this.getDepartments();
					}).catch(res=>{//删除失败
                        this.$message({
                            message: res.data.msg,
                            type: 'error'
                        });
					})
				}).catch(() => {//取消

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
                this.getTree();//点击修改就需要查询上级部门
			    this.title="编辑";
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);//回显
				//row表示当前行数据，department表示上级对象
				if(row.department){
                    let str=row.dirPath;   //     /1/12/63
                    let arr = str.split("/");//将字符串以 / 切割    得到结果[ "", "1", "12", "63" ]
                    //准备一个空数组
                    let department = [];
                    for (let i=1;i< arr.length-1;i++){
                        department.push(parseInt(arr[i]))
                    }
                    //console.log(department)
                    //重新赋值
                    this.editForm.department=department;
                }
			},
			//显示新增界面
			handleAdd: function () {
                this.title="添加";
                this.getEmployees();//点击添加就需要查询员工中1的领导
                this.getTree();//点击添加就需要查询上级部门
				this.editFormVisible = true;//弹出添加模态框
				this.editForm = {//清空缓存
					name: '',
					sn: '',
					state: 0,
                    employee:null,
                    department:null
				};
			},
			//添加/编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
							let arr=para.department;//数据【1，8】
							if(arr){//客户没有选上级部门，默认创建顶级部门
							    //获取需要的数据传入数据库
								let end = arr[arr.length-1];//最后一位的id，就是存入数据库的父级部门id
								para.department={"id":end};//拼成对象，重新设置进去
							}
							//发送请求-提交数据
							this.$http.put("/dept",para).then(res=>{
							    console.log(res)
                                this.editLoading = false;//关闭加载圈圈
                                this.editFormVisible = false;//关闭模态框
                                //操作成功后调用方法，刷新列表
                                this.$message({
                                    message: '操作成功',
                                    type: 'success'
                                });
                                this.getDepartments();
							}).catch(res=>{
                                this.$message({
                                    message: res.data.msg,
                                    type: 'error'
                                });
							})
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
			    //删除的id数组
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//发送请求
					this.$http.patch("/dept",ids).then(res=>{//删除成功
                        this.listLoading = false;//关闭加载圈圈
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        //删除成功后调用方法，刷新列表
                        this.getDepartments();
					}).catch(res=>{//删除失败
                        this.$message({
                            message: res.data.msg,
                            type: 'error'
                        });
					})
				}).catch(() => {//取消了

				});
			}
		},
		mounted() {
			this.getDepartments();
			this.getEmployees();
		}
	}

</script>

<style scoped>

</style>